package com.tianheng.modbus.socket;

/**************************************************
 * copyright (c) 2020, peng.cao@tianheng-uestc.com All Rights Reserved.
 * created by peng.cao
 * date:       2020/8/1 0001
 * since:      1.0.0.1
 * description:
 *
 **************************************************/

import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;
/**
 * 服务端
 */
public class Server {
    public static void main(String[] args) throws Exception {
        CRC crc= new CRC();
        // 监听指定的端口
        int port = 55533;
        ServerSocket server = new ServerSocket(port);

        // server将一直等待连接的到来
        System.out.println("server开启...");
        Socket socket = server.accept();
        System.out.println("客户端:"+socket.getInetAddress().getLocalHost()+"已连接到服务器");

        // 建立好连接后，从socket中获取输入流，并建立缓冲区进行读取
        InputStream inputStream = socket.getInputStream();
        byte[] bytes = new byte[1024];
        int len = inputStream.read(bytes);
        for (int i = 0; i < len; i++) {
            System.out.print(bytes[i]);
        }
        System.out.println();

        //截取校验位之前的数据
        byte[] a = new byte[12];
        for (int i = 0; i < a.length; i++) {
            a[i] = bytes[i];
        }
        //截取校验位
        byte[] check1 = new byte[4];
        for (int i = 0; i < check1.length; i++) {
            check1[i]=bytes[12+i];
        }

        byte[] check2 = crc.getCRC(a).getBytes();

        //如果客户端传过来的校验位和计算得到的校验位相等，则返回数据
        if(Arrays.equals(check2, check1)){
            byte[] rt = new byte[] {0x00, 0x01, 0x00, 0x03, 0x00, 0x04, 0x00, 0x13, 0x00, 0x05,0x00, 0x04, 0x00, 0x08 };
            byte[] check_digit = crc.getCRC(rt).getBytes();  //校验数据

            byte[] bb = new byte[18]; //组合校验位后的数组

            //把原始数据和校验位组合到bb数组中
            System.arraycopy(rt, 0, bb, 0, rt.length);
            for (int i = 0; i < check_digit.length; i++) {
                bb[14+i]=check_digit[i];
            }

            socket.getOutputStream().write(bb);
        }
        //inputStream.close();
        socket.close();
        server.close();
    }
}
